package com.campus.help.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.help.entity.LaborApplication;
import com.campus.help.entity.Labor;
import com.campus.help.mapper.LaborApplicationMapper;
import com.campus.help.mapper.LaborMapper;
import com.campus.help.service.ApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 申请记录服务实现类
 *
 * @author campus-help
 * @since 2025-09-18
 */
@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService {

    @Autowired
    private LaborApplicationMapper laborApplicationMapper;

    @Autowired
    private LaborMapper laborMapper;

    @Override
    public Map<String, Object> getApplicationRecords(Long studentId, String status) {
        try {
            // 查询劳务申请记录
            List<Map<String, Object>> records = new ArrayList<>();
            
            // 构建查询条件
            QueryWrapper<LaborApplication> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("applicant_id", studentId)
                       .eq("deleted", 0)
                       .orderByDesc("application_time");
            
            if (status != null && !status.isEmpty()) {
                queryWrapper.eq("status", status);
            }
            
            List<LaborApplication> laborApplications = laborApplicationMapper.selectList(queryWrapper);
            
            // 转换为前端需要的格式
            for (LaborApplication application : laborApplications) {
                Map<String, Object> record = new HashMap<>();
                record.put("id", application.getId());
                record.put("applicationType", "labor");
                record.put("status", application.getStatus());
                record.put("applicationTime", application.getApplicationTime());
                record.put("reviewTime", application.getReviewTime());
                record.put("completeTime", application.getCompleteTime());
                record.put("applicationNote", application.getApplicationNote());
                record.put("reviewNote", application.getReviewNote());
                record.put("completeNote", application.getCompleteNote());
                
                // 查询关联的劳务信息
                try {
                    Labor labor = laborMapper.selectById(application.getLaborId());
                    if (labor != null) {
                        record.put("title", labor.getJobTitle());
                        record.put("description", labor.getDescription());
                        record.put("reward", labor.getSalary());
                        record.put("location", labor.getLocation());
                        record.put("workType", labor.getWorkType());
                    } else {
                        record.put("title", "劳务申请");
                        record.put("description", application.getApplicationNote() != null ? 
                            application.getApplicationNote() : "劳务服务申请");
                        record.put("reward", 0.0);
                    }
                } catch (Exception e) {
                    log.warn("获取劳务信息失败: laborId={}, error={}", application.getLaborId(), e.getMessage());
                    record.put("title", "劳务申请");
                    record.put("description", application.getApplicationNote() != null ? 
                        application.getApplicationNote() : "劳务服务申请");
                    record.put("reward", 0.0);
                }
                
                records.add(record);
            }
            
            // 统计信息
            Map<String, Object> stats = getApplicationStats(studentId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("records", records);
            result.put("stats", stats);
            
            return result;
        } catch (Exception e) {
            log.error("获取申请记录失败", e);
            throw new RuntimeException("获取申请记录失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelApplication(Long studentId, Long applicationId, String applicationType) {
        try {
            if ("labor".equals(applicationType)) {
                // 取消劳务申请
                LaborApplication application = laborApplicationMapper.selectById(applicationId);
                if (application == null) {
                    throw new RuntimeException("申请记录不存在");
                }
                
                if (!application.getApplicantId().equals(studentId)) {
                    throw new RuntimeException("无权限操作此申请");
                }
                
                if (!"pending".equals(application.getStatus())) {
                    throw new RuntimeException("只能取消待审核状态的申请");
                }
                
                application.setStatus("cancelled");
                application.setUpdateTime(LocalDateTime.now());
                laborApplicationMapper.updateById(application);
                
                log.info("学生取消劳务申请: studentId={}, applicationId={}", studentId, applicationId);
            } else {
                throw new RuntimeException("不支持的申请类型: " + applicationType);
            }
        } catch (Exception e) {
            log.error("取消申请失败", e);
            throw new RuntimeException("取消申请失败", e);
        }
    }

    /**
     * 获取申请统计信息
     */
    private Map<String, Object> getApplicationStats(Long studentId) {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 查询各种状态的申请数量
            QueryWrapper<LaborApplication> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("applicant_id", studentId)
                       .eq("deleted", 0);
            
            Long total = laborApplicationMapper.selectCount(queryWrapper);
            stats.put("total", total.intValue());
            
            queryWrapper.eq("status", "pending");
            Long pending = laborApplicationMapper.selectCount(queryWrapper);
            stats.put("pending", pending.intValue());
            
            queryWrapper.clear();
            queryWrapper.eq("applicant_id", studentId)
                       .eq("deleted", 0)
                       .eq("status", "accepted");
            Long accepted = laborApplicationMapper.selectCount(queryWrapper);
            stats.put("accepted", accepted.intValue());
            
            queryWrapper.clear();
            queryWrapper.eq("applicant_id", studentId)
                       .eq("deleted", 0)
                       .eq("status", "rejected");
            Long rejected = laborApplicationMapper.selectCount(queryWrapper);
            stats.put("rejected", rejected.intValue());
            
            queryWrapper.clear();
            queryWrapper.eq("applicant_id", studentId)
                       .eq("deleted", 0)
                       .eq("status", "completed");
            Long completed = laborApplicationMapper.selectCount(queryWrapper);
            stats.put("completed", completed.intValue());
            
        } catch (Exception e) {
            log.error("获取申请统计信息失败", e);
            // 设置默认值
            stats.put("total", 0);
            stats.put("pending", 0);
            stats.put("accepted", 0);
            stats.put("rejected", 0);
            stats.put("completed", 0);
        }
        
        return stats;
    }
}
